using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Network.Tcp.NetSession;

namespace Network.Tcp.Pooling
{
    public class SessionPool : ObjectPool<Session>
    {
        private Func<Session> _createMethod;
        private Action<Session> _cleanMethod;
        #region 初始会话池
        public SessionPool Initialize(Func<Session> createSaea, Action<Session> cleanSaea, int initialCount = 0)
        {
            //创建对象的方法
            _createMethod = createSaea ?? throw new ArgumentNullException("createSaea");
            //清理对象的方法
            _cleanMethod = cleanSaea ?? throw new ArgumentNullException("cleanSaea");
            //初始数量不能小于0
            if (initialCount < 0)
                throw new ArgumentOutOfRangeException(
                    "initialCount",
                    initialCount,
                    "Initial count must not be less than zero.");

            for (int i = 0; i < initialCount; i++)
            {
                Add(Create());
            }
            return this;
        }
        #endregion
        #region 创建对象
        protected override Session Create()
        {
            return _createMethod();
        }
        #endregion
        #region 清理并返还对象
        public void Return(Session saea)
        {
            _cleanMethod(saea);
            Add(saea);
        }
        #endregion
    }
}
